package com.java.jvm.demo.chapter04;

import java.io.*;

/**
 * @author wangning
 * @create 2021-12-23 21:21
 * 自定义ClassLoader
 */
public class MyClassLoader extends ClassLoader {
	private String byteCodePath;

	public MyClassLoader(String byteCodePath) {
		this.byteCodePath = byteCodePath;
	}

	public MyClassLoader(ClassLoader parent, String byteCodePath) {
		super(parent);
		this.byteCodePath = byteCodePath;
	}

	@Override
	protected Class<?> findClass(String name) {
		BufferedInputStream bis = null;
		ByteArrayOutputStream baos = null;

		try {
			//获取字节码文件的完整路径
			String fileName = byteCodePath + name + ".class";
			//获取一个输入流
			bis = new BufferedInputStream(new FileInputStream(""));
			//获取一个输出流
			baos = new ByteArrayOutputStream();
			//具体读入数据并写出过程
			int len;
			byte[] data = new byte[1024];
			while ((len = bis.read(data)) != -1) {
				baos.write(data, 0, len);
			}
			//获取内存中的完整的字节数组的数据
			byte[] bytes = baos.toByteArray();
			//调用defineClass(),将租借数组的数据转换为class的实例
			Class clazz = defineClass(null, bytes, 0, bytes.length);
			return clazz;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {

					baos.close();

				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (bis != null) {

					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}
}
